module LoginSystem
  protected
  def is_logged_in?    
    if session[:user].nil?
      if !cookies[:login].nil?
        loginuser=cookies[:login]
        userpassword=loginuser.split(":")
        if userpassword.length >= 2
          username=userpassword[0]
          password=userpassword[1]
          @logged_in_user = User.authenticate(username, password)
          if !@logged_in_user.nil?
            session[:user]=@logged_in_user.id;
          end
        end
      end
    end
    @logged_in_user = User.find(session[:user]) if session[:user]
  end
  
  def logged_in_user
    return @logged_in_user if is_logged_in?
  end
  
  def logged_in_user=(user)
    if !user.nil?
      session[:user] = user.id
      @logged_in_user = user
    end
  end
  
  def self.included(base)
    base.send :helper_method, :is_logged_in?, :logged_in_user
  end
end